import sys
import numpy as np
import matplotlib.pyplot as plt

def press(event):
	print('press',event.key)
	sys.stdout.flush()
	if event.key=='x':
		visible=x1.get_visible()
		x1.set_visible(not visible)
		fig.canvas.draw()

def OnClick(event):  
    global Coords1x,Coords1y  
    global Coords3x,Coords3y  
    #ax = plt.gca()  
    if event.button ==1:  
        Coords1x = event.xdata  
        Coords1y = event.ydata  
    if event.button == 3:  
        Coords3x = event.xdata  
        Coords3y = event.ydata 

def OnMouseMotion(event):  
    global Coords2x,Coords2y,x1,y1  
    if event.button == 1:  
        Coords2x = event.xdata  
        Coords2y = event.ydata  
        x1 = [Coords1x,Coords2x]  
        y1 = [Coords1y,Coords2y]  
        # a=(Coords1y - Coords2y)/(Coords1x - Coords2x)
        # b=Coords1y-a*Coords1x
        # x1 = [-1,2]  
        # y1 = [-1*a+b,2*a+b]         
        ax = plt.gca()  
        lines = ax.plot(x1,y1,picker = 20)  
        # print(lines)
        ax.figure.canvas.draw()  
        #删除之前的线条，进行更新  
        l = lines.pop(0)  
        l.remove()  
        del l  
    elif event.button == 3:  
        Coords4x = event.xdata  
        Coords4y = event.ydata  
        x2 = [Coords3x,Coords4x]  
        y2 = [Coords3y,Coords4y]  
        ax1 = plt.gca()  
        #lines = ax1.plot(x1,y1,picker = 5)  
        lines1 = ax1.plot(x2,y2,picker = 20)  
        ax1.figure.canvas.draw()  
        #删除之前的线条，进行更新  
        l = lines1.pop(0)  
        l.remove()  
        del l

def OnRelease(event):
    global Coords1x,Coords2x,Coords1y,Coords2y
    # x1 = [Coords1x,Coords2x]  
    # y1 = [Coords1y,Coords2y]  
    if Coords1x==Coords2x:
        a=0
    else:
        a=(Coords1y - Coords2y)/(Coords1x - Coords2x)
    b=Coords1y-a*Coords1x
    x1 = [0,1]  
    y1 = [b,a+b] 
    ax1=plt.gca()
    lines1=ax1.plot(x1,y1,picker=20)
    ax1.figure.canvas.draw()

def OnPick(event):
    line=event.artist
    line.remove()
    del line
    # xdata,ydata=line.get_data()
    # ind=event.ind
    # print('on pick line',np.array([xdata[ind],ydata[ind]]))

np.random.seed(19680801)

fig,ax=plt.subplots()

# tbar=fig.get_navigation_toolbar()

fig.canvas.mpl_connect('key_press_event',press)
ax.set_xlabel('easy come,easy go')
x1=ax.get_xaxis()

ax.plot(np.random.rand(12),np.random.rand(12),'go')
ax.set_title('press a key')

fig.canvas.mpl_connect('button_press_event',OnClick)  
fig.canvas.mpl_connect('button_release_event',OnRelease)
fig.canvas.mpl_connect('motion_notify_event',OnMouseMotion) 
fig.canvas.mpl_connect('pick_event',OnPick)

plt.show()